package kyuuri.server;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GarbageCollector extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, final HttpServletResponse resp) {
		try {
			PrintWriter out = resp.getWriter();
			PersistenceManager pm = PMF.get().getPersistenceManager();
			Query query = pm.newQuery(NicoLive.class);
			
			GregorianCalendar calendar = new GregorianCalendar();
			calendar.add(calendar.MINUTE, -30);
			
			Date date = new Date();
			date.setTime(calendar.getTimeInMillis());
			query.declareImports("import java.util.Date");
			query.setFilter("broadcasting == true && pubDate < date");
			query.declareParameters("Date date");
			try {
				List<NicoLive> results = (List<NicoLive>) query.execute(date);
				if (results.iterator().hasNext()) {
					for (NicoLive live : results) {
						live.setBroadcasting(false);
					}
				}
			} finally {
				query.closeAll();
				pm.close();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
